package org.nimi317.web_gis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nimi317.web_gis.data.AreaCodeList;
import org.nimi317.web_gis.exception.E;
import org.nimi317.web_gis.exception.RException;
import org.nimi317.web_gis.dao.CurrentMapper;
import org.nimi317.web_gis.entity.Current;
import org.nimi317.web_gis.entity.TableRange;
import org.nimi317.web_gis.service.ICurrentService;
import org.nimi317.web_gis.service.ITableRangeService;
import org.springframework.context.annotation.Lazy;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author thunderobot
 */
@Service
@Transactional
public class ICurrentServiceImpl extends ServiceImpl<CurrentMapper, Current> implements ICurrentService {

    private final AreaCodeList codeList;

    private final ITableRangeService tableRangeService;

    private final JdbcTemplate template;

    public ICurrentServiceImpl(@Lazy AreaCodeList codeList, ITableRangeService tableRangeService, JdbcTemplate template) {
        this.codeList = codeList;
        this.tableRangeService = tableRangeService;
        this.template = template;
    }

    @Override
    public String getCurrentDB() {
        LambdaQueryWrapper<Current> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNotNull(Current::getTableName);
        Current one = this.getOne(wrapper);
        return one.getTableName();
    }

    @Override
    public void updateCurrentDB(String dbName) {
        LambdaQueryWrapper<TableRange> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TableRange::getTableName, dbName);
        boolean exists = tableRangeService.exists(wrapper);
        if (!exists) {
            throw new RException(E.DataTableNotFoundException);
        }
        template.update("UPDATE current SET table_name = ? where table_name=?", ps -> {
            ps.setString(1, dbName);
            ps.setString(2, codeList.getTableName());
        });
        codeList.setTableName(dbName);
    }
}
